package com.ghl.crawler.core;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description
 * @Author haiLong <1105744725@qq.com>
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2019/11/7 15:44
 */
public class DBHelper {

    // GC不理static
    private static SqlSessionFactory factory = null;

    public static SqlSessionFactory getSqlSessionFactory() {
        if (factory == null) {
            String resource = "mybatis/mybatis-config.xml";
            InputStream inputStream = null;
            try {
                inputStream = Resources.getResourceAsStream(resource);
            } catch (IOException e) {
                e.printStackTrace();
            }
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        }
        return factory;
    }

    /**
     * @return 获得得sql会话
     */
    public static SqlSession getSession() {
        return getSqlSessionFactory().openSession(true);
    }

    /**
     * 获得得sql会话
     *
     * @param isAutoCommit 是否自动提交，如果为false则需要sqlSession.commit();rollback();
     * @return sql会话
     */
    public static SqlSession getSession(boolean isAutoCommit) {
        return getSqlSessionFactory().openSession(isAutoCommit);
    }
}
